/*
 * CorregimientosAgregarFrame.java
 *
 * Created on 27 de abril de 2008, 03:40 PM
 */
package org.contabilidad.municipios;

import org.mybeans.Sesion;
import org.mybeans.CorregimientosBeans;
 
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;

/**
 *
 * @author  avbravo
 */
public class CorregimientosAgregarFrame extends javax.swing.JFrame {

    Sesion sesion;
    CorregimientosBeans corregimientosBeans;

    /** Creates new form CorregimientosAgregarFrame */
    public CorregimientosAgregarFrame() {
        initComponents();
        /*
         * Fondo
         */

        
          
         

         
         

        /*
         * fin del fondo
         */
        sesion = new Sesion();
        corregimientosBeans = new CorregimientosBeans();
        CargarProvincias();
//        CargarMunicipios();
 AutoCompleteDecorator.decorate(this.jComboBoxMunicipio);
 AutoCompleteDecorator.decorate(this.jComboBoxProvincia);
 NuevoNumeroCorregimiento();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTextFieldIdCorregimiento = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldCorregimiento = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jComboBoxMunicipio = new javax.swing.JComboBox();
        jButtonGuardar = new javax.swing.JButton();
        jButtonLimpiar = new javax.swing.JButton();
        jButtonRegresar = new javax.swing.JButton();
        jLabel15 = new javax.swing.JLabel();
        jComboBoxProvincia = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Agregar Corregimientos");

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Numero");

        jTextFieldIdCorregimiento.setEditable(false);
        jTextFieldIdCorregimiento.setEnabled(false);

        jLabel2.setText("Corregimiento");

        jLabel3.setText("Municipio");

        jComboBoxMunicipio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxMunicipioActionPerformed(evt);
            }
        });

        jButtonGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/save.png"))); // NOI18N
        jButtonGuardar.setToolTipText("Guardar");
        jButtonGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonGuardarActionPerformed(evt);
            }
        });

        jButtonLimpiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/escoba.png"))); // NOI18N
        jButtonLimpiar.setToolTipText("Limpiar");
        jButtonLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonLimpiarActionPerformed(evt);
            }
        });

        jButtonRegresar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/regresar.jpeg"))); // NOI18N
        jButtonRegresar.setToolTipText("Regresar");
        jButtonRegresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonRegresarActionPerformed(evt);
            }
        });

        jLabel15.setText("Provincia");

        jComboBoxProvincia.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jComboBoxProvinciaItemStateChanged(evt);
            }
        });
        jComboBoxProvincia.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxProvinciaActionPerformed(evt);
            }
        });
        jComboBoxProvincia.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jComboBoxProvinciaKeyReleased(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(54, 54, 54)
                        .addComponent(jButtonGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButtonLimpiar, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButtonRegresar, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel15)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3)
                            .addComponent(jLabel1))
                        .addGap(4, 4, 4)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTextFieldIdCorregimiento, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jComboBoxMunicipio, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTextFieldCorregimiento, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jComboBoxProvincia, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(264, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel15)
                    .addComponent(jComboBoxProvincia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jComboBoxMunicipio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextFieldIdCorregimiento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextFieldCorregimiento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 41, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButtonLimpiar, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonRegresar, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButtonGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGuardarActionPerformed
 
    try {

        String idCorregimiento = this.jTextFieldIdCorregimiento.getText();
        if (idCorregimiento == null || idCorregimiento.equals("")) {
            JOptionPane.showMessageDialog(this, "Ingrese el codigo", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            jTextFieldIdCorregimiento.requestFocus();
            return;
        }

        String Corregimiento = this.jTextFieldCorregimiento.getText();
        if (Corregimiento == null || Corregimiento.equals("")) {
            JOptionPane.showMessageDialog(this, "Ingrese el corregimiento", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            jTextFieldCorregimiento.requestFocus();
            return;
        }

        String Municipio = (String) this.jComboBoxMunicipio.getSelectedItem();
        if (Municipio == null || Municipio.equals("")) {
            JOptionPane.showMessageDialog(this, "seleccione el municipio ", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        String IdMunicipio = BuscarMunicipios(Municipio);

        if (sesion.Conectar() == false) {
            JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        String sqlquery = "select * from corregimients where idcorregimiento = ?";
        PreparedStatement psquery = sesion.con.prepareStatement(sqlquery);
        psquery.setString(1, idCorregimiento);
        ResultSet rs = psquery.executeQuery();
        rs.next();
        int x = rs.getRow();

        if (x != 0) {
            JOptionPane.showMessageDialog(this, "Existe un corregimiento con ese codigo", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        String sql = "INSERT into corregimients (idcorregimiento, corregimiento, idmunicipio) VALUES(?,?,?)";
        PreparedStatement prest = sesion.con.prepareStatement(sql);

        prest.setString(1, idCorregimiento);
        prest.setString(2,Corregimiento);
        prest.setString(3, IdMunicipio);

        int count = prest.executeUpdate();
        sesion.con.close();
        JOptionPane.showMessageDialog(this, "Corregimiento Guardado exitosamente", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
        corregimientosBeans.setIdCorregimiento(idCorregimiento);
        corregimientosBeans.setCorregimiento(Corregimiento);
        corregimientosBeans.setIdMunicipio(IdMunicipio);
         jTextFieldIdCorregimiento.setText("");
    jTextFieldCorregimiento.setText("");
    NuevoNumeroCorregimiento();
    } catch (Exception ex) {
        System.out.println("Error" + ex);
        JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    }
}//GEN-LAST:event_jButtonGuardarActionPerformed

private void jButtonLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLimpiarActionPerformed
 
    jTextFieldIdCorregimiento.setText("");
    jTextFieldCorregimiento.setText("");
    NuevoNumeroCorregimiento();
}//GEN-LAST:event_jButtonLimpiarActionPerformed

private void jButtonRegresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRegresarActionPerformed
 
    dispose();
}//GEN-LAST:event_jButtonRegresarActionPerformed

private void jComboBoxProvinciaItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBoxProvinciaItemStateChanged
    // TODO add your handling code here:
}//GEN-LAST:event_jComboBoxProvinciaItemStateChanged

private void jComboBoxProvinciaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxProvinciaActionPerformed
    // TODO add your handling code here:
    String provincia = (String) jComboBoxProvincia.getSelectedItem();
    String idProvincia = BuscarProvincias(provincia);
    CargarMunicipios(idProvincia, false);
}//GEN-LAST:event_jComboBoxProvinciaActionPerformed

private void jComboBoxProvinciaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jComboBoxProvinciaKeyReleased
    // TODO add your handling code here:
}//GEN-LAST:event_jComboBoxProvinciaKeyReleased

private void jComboBoxMunicipioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxMunicipioActionPerformed
    // TODO add your handling code here:
}//GEN-LAST:event_jComboBoxMunicipioActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new CorregimientosAgregarFrame().setVisible(true);
            }
        });
    }

    private String BuscarMunicipios(String Municipio) {
        try {
            if (sesion.Conectar() == false) {
                JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return "";
            }

            String sqlquery = "select * from municipies where municipio = ? ";
            PreparedStatement psquery = sesion.con.prepareStatement(sqlquery);
            psquery.setString(1, Municipio);

            ResultSet rs = psquery.executeQuery();
            rs.next();
            int x = rs.getRow();

            if (x == 0) {
                JOptionPane.showMessageDialog(this, "no existe un municipio con ese nombre", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return "";
            }
            return rs.getString("idmunicipio");


        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
        return "";
    }

          public void CargarMunicipios(String idProvincia, boolean comboCorregimientoActual) {
        try {
            if (sesion.Conectar() == false) {
                JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            PreparedStatement psquery;
            if (idProvincia.equals("")) {
                //cuando se quiere mostrar todos los corregimientos
                String sqlquery = "select idmunicipio, municipio from municipies ";
                psquery = sesion.con.prepareStatement(sqlquery);

            } else {
                String sqlquery = "select idmunicipio, municipio  from municipies where idprovincia = ?";
                psquery = sesion.con.prepareStatement(sqlquery);
                psquery.setString(1, idProvincia);
            }
            ResultSet rs = psquery.executeQuery();

                jComboBoxMunicipio.removeAllItems();


            int count = 0;
            while (rs.next()) {
                String municipio = rs.getString("municipio");
                    jComboBoxMunicipio.insertItemAt(municipio, count);

                count++;
            }
                if (count != 0) {
                    jComboBoxMunicipio.setSelectedIndex(0);
                }

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error Cargando Corregimientos" + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
       private void CargarProvincias() {
        try {
            if (sesion.Conectar() == false) {
                JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            String sqlquery = "select idprovincia, provincia  from provinces order by provincia";
            PreparedStatement psquery = sesion.con.prepareStatement(sqlquery);
            ResultSet rs = psquery.executeQuery();
            jComboBoxProvincia.removeAllItems();
            int count = 0;
            while (rs.next()) {
                String provincia = rs.getString("provincia");
                jComboBoxProvincia.insertItemAt(provincia, count);

                count++;
            }
            if (count != 0) {
                jComboBoxProvincia.setSelectedItem(1);
            }


        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error Cargando provincias" + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

        private String BuscarProvincias(String provincia) {
        try {
            if (sesion.Conectar() == false) {
                JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return "";
            }

            String sqlquery = "select * from provinces where provincia = ? ";
            PreparedStatement psquery = sesion.con.prepareStatement(sqlquery);
            psquery.setString(1, provincia);

            ResultSet rs = psquery.executeQuery();
            rs.next();
            int x = rs.getRow();

            if (x == 0) {
                JOptionPane.showMessageDialog(this, "no existe una provincia con  ese nombre", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
sesion.con.close();
                return "";
            }

            return rs.getString("idprovincia");


        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error Cargando Provincias" + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
        return "";
    }

         private void NuevoNumeroCorregimiento() {
        try {
            //   int NuevoNumeroRecibo = recibesBeans.getNumeroReciboDisponible();
            int NuevoNumero = corregimientosBeans.CorregimientoUltimo();
            if (NuevoNumero != -1) {
                NuevoNumero++;
                jTextFieldIdCorregimiento.setText(String.valueOf(NuevoNumero));

            } else {
                sesion.MostrarMensajeInformacion("Mensaje", "No se genero ningun numero corregimientos");
            }
        } catch (Exception ex) {
            sesion.MostrarMensajeError("Error ", "CrearNuevoRecibo()\n " + ex.getMessage().toString());
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonGuardar;
    private javax.swing.JButton jButtonLimpiar;
    private javax.swing.JButton jButtonRegresar;
    private javax.swing.JComboBox jComboBoxMunicipio;
    private javax.swing.JComboBox jComboBoxProvincia;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField jTextFieldCorregimiento;
    private javax.swing.JTextField jTextFieldIdCorregimiento;
    // End of variables declaration//GEN-END:variables
}
